import jsonfetch

class Listing(object):
  def __init__(self, children):
    self.items = []
    for item in children:
      if isinstance(item, dict):
        data = item['data']
        item = Item(name=data['name'],
                    url=data['url'],
                    title=data['title'],
                    author=data['author'],
                    created=data['created'],
                    over_18=data['over_18'],
                    )
      self.items.append(item)

  def __len__(self):
    return len(self.items)

  def __getitem__(self, i):
    return self.items[i]

  @classmethod
  def get(cls, reddit, reddit_site='reddit.com'):
    url = 'http://%s/r/%s.json' % (reddit_site, reddit)
    data = jsonfetch.get(url)['data']
    return Listing(data['children'])


class Item(object):
  def __init__(self, name, url, title, author, created, over_18=False):
    self.name = name
    self.url = url
    self.title = title
    self.author = author
    self.created = created
    self.over_18 = over_18

  def __str__(self):
    return '<%s> %s %s%s' % (
        self.author, self.title, self.url, self.over_18 and ' [NSFW]' or '')


if __name__ == '__main__':
  for item in Listing.get('programming'):
    print item
